package com.casic.ops.runner.pipeline.manager;

import com.casic.ops.entity.domain.MachineInfoDO;
import com.casic.ops.handler.pipeline.PipelineExecuteLoggerSocketService;
import com.casic.ops.utils.ValueMix;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Session缓存管理 ，现在已经抛弃了该ssh连接方式
 * @author cww
 * @date 2022//6/17
 */
@Slf4j
@Service
public class SessionManager {
//
//    private ConcurrentHashMap<String, MachineInfo> cached = new ConcurrentHashMap<>(2 << 4);
//
//    @Resource
//    private BuilderMachineManager builderMachineManager;

    private MachineInfoDO machineInfoDO;

    /**
     * 缓存中有空闲的session则复用，没有则选择使用最少的构建服务器进行创建
     * @return
     */
    public synchronized Session get() throws Exception {
        // 随机获取一台构建服务器
//        MachineInfo builderMachine = builderMachineManager.getRandom();
        Session session = null;
        JSch jsch = new JSch();
        session = jsch.getSession(machineInfoDO.getUsername(), machineInfoDO.getMachineHost(), machineInfoDO.getSshPort());
        // 解密并设置密码
        session.setPassword(ValueMix.decrypt(machineInfoDO.getPassword()));

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        // 为Session对象设置properties
        session.setConfig(config);
        // 设置timeout时间
        session.setTimeout(5000000);
        // 通过Session建立链接
        session.connect();
        return session;
    }

    public void setMachineInfoDO(MachineInfoDO machineInfoDO){
        this.machineInfoDO=machineInfoDO;
    }
}
